package com.example.big_upload.utils;

import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;

public class CheckUtil {

    public static String generateSHA256(InputStream is) {
        StringBuilder sb = new StringBuilder();
        try {
            MessageDigest instance = MessageDigest.getInstance("SHA-256");
            byte[] buf = new byte[8192];
            int count = 0;
            // 读取文件内容并更新摘要
            while ((count = is.read(buf)) != -1) {
                instance.update(buf, 0, count);
            }
            // 完成哈希计算
            byte[] bytes = instance.digest();
            // 将得到的字节转换成十六进制字符串
            for (byte b : bytes) {
                sb.append(String.format("%02x", b));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null){
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

    public static String generateSHA256(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        try {
            MessageDigest instance = MessageDigest.getInstance("SHA-256");
            byte[] res = instance.digest(bytes);
            // 将得到的字节转换成十六进制字符串
            for (byte b : res) {
                sb.append(Integer.toHexString((b & 0xff) + 0x100).substring(1));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

}
